package org.lansir.af.reminder;

import java.util.Calendar;

import org.lansir.af.database.Database;
import org.lansir.af.util.Utils;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;

/**
 * 
 * @author 蓝智宏
 *
 */
public class AlarmService extends Service {

	private Database db;
	private Context context;
	private Utils utils;
	private DataViewAlarm dataViewAlarm;
	private Handler handlerUpdateDate = new Handler();
	private Calendar dateToday = Calendar.getInstance();
	private final static int iHandlerUpdateTime = 1000 * 3;
	private int iUpdateDate_minute = 0;
	
	private AlarmReminder alarmReminder = null;
	
	private Runnable handlerUpdateDateTask = new Runnable() {
		@Override
		public void run() {
			try {
				updateTodayDate();
				// refresh data, if system timer minute changed
				if (iUpdateDate_minute != dateToday.get(Calendar.MINUTE)) {
					refreshAlarmData();
				}
			} finally {
				handlerUpdateDate.postDelayed(this, iHandlerUpdateTime);
			}
		}
	};
	
	
	
	
	@Override
	public void onCreate() {
		super.onCreate();
		db = new Database(this);
		context = getApplicationContext();
		dataViewAlarm = new DataViewAlarm(this, db);
		utils = new Utils(this);
		alarmReminder = new AlarmReminder(this,context, utils);
		// schedule handler update date task
		handlerUpdateDate.removeCallbacks(handlerUpdateDateTask);
		handlerUpdateDate
				.postDelayed(handlerUpdateDateTask, iHandlerUpdateTime);
		Log.v("ActivityFairy", "Service created");
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		alarmReminder.removeNotify();
		handlerUpdateDate.removeCallbacks(handlerUpdateDateTask);
	}
	
	public synchronized void updateTodayDate() {
		dateToday.setTimeInMillis(System.currentTimeMillis());
		//dateToday.setFirstDayOfWeek(prefs.iFirstDayOfWeek);
	}
	
	private synchronized void refreshAlarmData() {
		iUpdateDate_minute = dateToday.get(Calendar.MINUTE);
		if (dataViewAlarm.collectAlarmItems()) {
			alarmReminder.clear();
			alarmReminder.addAlarmData(dataViewAlarm.getDataViewItemAlarms());
			//reminder.AddAlarmData(dataView.GetTasksData());
			alarmReminder.showNotification();
		}
	}
	

	

	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	
}
